//
//  GZUserAccountViewModel.swift
//  sinaweibo
//
//  Created by mac book pro on 16/3/22.
//  Copyright © 2016年 finish. All rights reserved.
//

import UIKit

class GZUserAccountViewModel: NSObject {
    static let sharedInstance = GZUserAccountViewModel()
    var userAccount: GZUserAccount?
    private override init() {
        super.init()
        userAccount = loadUserInfo()
        
    }
    var userLogin: Bool{
        get{
            return userAccount != nil
        }
        
    }
    func loadUserInfos(callback:(error:NSError?)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters: [String:AnyObject] = ["access_token": userAccount!.access_token!, "uid": userAccount!.uid!]
        //        GZAFNetworkTool.sharedNetworkTool.afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        //                self.userAccount?.screen_name = result?["screen_name"] as? String
        //                self.userAccount?.avatar_large = result?["avatar_large"] as? String
        //                self.saveUserInfo()
        //                callback(error: nil)
        //
        //            }) { (_, error) -> Void in
        //                callback(error: error)
        //        }
        GZAFNetworkTool.sharedNetworkTool.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            if result != nil{
                self.userAccount?.screen_name = result?["screen_name"] as? String
                self.userAccount?.avatar_large = result?["avatar_large"] as? String
                self.saveUserInfo()
                callback(error: nil)
            }else{
                callback(error: error)
            }
        }
        
    }
    func loadAccessToken(code: String,compication: (error: NSError?)->()){
        let url = "\(sinatokenapi)"
        let parameters = [ "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri]
        
        //        //发送请求
        //        GZAFNetworkTool.sharedNetworkTool.afnManager.POST(url, parameters: parameters, progress: nil, success: { (_, responseObj) -> Void in
        //            self.userAccount = GZUserAccount(dict: responseObj as! [String : AnyObject])
        //            //沙盒缓存
        //            self.saveUserInfo()
        //            compication(error: nil)
        //
        //            }, failure: { (_, error2) -> Void in
        //                compication(error: error2)
        //        })
        GZAFNetworkTool.sharedNetworkTool.requestPOST(url, parameters: parameters) { (result, error) -> () in
            if result != nil{
                self.userAccount = GZUserAccount(dict:result!)
                //沙盒缓存
                self.saveUserInfo()
                compication(error: nil)
            }else{
                compication(error: error)
            }
        }
        
    }
    let userAccoutPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/UserAccount.plist")
    
    private func saveUserInfo(){
        if (userAccount != nil) {
            print("\(userAccoutPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: userAccoutPath!)
        }
    }
    private func loadUserInfo() -> GZUserAccount?{
        let loaduser = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccoutPath!) as? GZUserAccount
        if loaduser != nil && loaduser!.expiresDate!.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return loaduser!
        }
        return nil
        
    }
}
